import express from 'express'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import { authenticateToken } from '../middleware/auth.js'
import db, { generateId, initDatabase } from '../db/database.js'

const router = express.Router()

// 初始化数据库（如果还没有初始化）
initDatabase()

// 注册
router.post('/register', async (req, res, next) => {
  try {
    const { username, email, password } = req.body

    if (!username || !email || !password) {
      return res.status(400).json({
        code: 400,
        message: '请提供用户名、邮箱和密码',
        success: false
      })
    }

    // 检查用户是否已存在
    const existingUser = db.prepare('SELECT id FROM users WHERE username = ? OR email = ?').get(username, email)
    if (existingUser) {
      return res.status(400).json({
        code: 400,
        message: '用户名或邮箱已存在',
        success: false
      })
    }

    // 加密密码
    const passwordHash = await bcrypt.hash(password, 10)

    // 创建用户
    const userId = generateId()
    db.prepare(`
      INSERT INTO users (id, username, email, password_hash)
      VALUES (?, ?, ?, ?)
    `).run(userId, username, email, passwordHash)

    // 生成JWT令牌
    const token = jwt.sign(
      { userId, username },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: process.env.JWT_EXPIRES_IN || '7d' }
    )

    res.json({
      code: 200,
      message: '注册成功',
      success: true,
      data: {
        token,
        user: {
          id: userId,
          username,
          email,
          createdAt: new Date().toISOString()
        }
      }
    })
  } catch (error) {
    next(error)
  }
})

// 登录
router.post('/login', async (req, res, next) => {
  try {
    const { username, password } = req.body

    if (!username || !password) {
      return res.status(400).json({
        code: 400,
        message: '请提供用户名和密码',
        success: false
      })
    }

    // 查找用户
    const user = db.prepare('SELECT * FROM users WHERE username = ? OR email = ?').get(username, username)
    if (!user) {
      return res.status(401).json({
        code: 401,
        message: '用户名或密码错误',
        success: false
      })
    }

    // 验证密码
    const isValid = await bcrypt.compare(password, user.password_hash)
    if (!isValid) {
      return res.status(401).json({
        code: 401,
        message: '用户名或密码错误',
        success: false
      })
    }

    // 生成JWT令牌
    const token = jwt.sign(
      { userId: user.id, username: user.username },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: process.env.JWT_EXPIRES_IN || '7d' }
    )

    res.json({
      code: 200,
      message: '登录成功',
      success: true,
      data: {
        token,
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          createdAt: user.created_at
        }
      }
    })
  } catch (error) {
    next(error)
  }
})

// 获取用户信息（需要认证）
router.get('/profile', authenticateToken, async (req, res, next) => {
  try {
    const userId = req.user.userId
    if (!userId) {
      return res.status(401).json({
        code: 401,
        message: '未认证',
        success: false
      })
    }

    const user = db.prepare('SELECT id, username, email, created_at FROM users WHERE id = ?').get(userId)
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        success: false
      })
    }

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        id: user.id,
        username: user.username,
        email: user.email,
        createdAt: user.created_at
      }
    })
  } catch (error) {
    next(error)
  }
})

export default router

